import re
import subprocess
from typing import Any

from PySide6.QtGui import Qt
from PySide6.QtWidgets import QWidget, QHBoxLayout, QVBoxLayout, QCompleter
from qfluentwidgets import (
    PushButton,
    InfoBar,
    InfoBarPosition,
    BodyLabel,
    MessageBoxBase,
    SubtitleLabel,
    ComboBox,
    EditableComboBox,
)
from app.utils.db import LocalCache
from app.utils.log_rec import logger


class SetAerodrome(MessageBoxBase):

    def __init__(self, parent=None):
        super().__init__(parent)
        self.label_title = SubtitleLabel()
        self.label_title.setText("设置机场信息")

        layout = QHBoxLayout()
        self.label_4 = BodyLabel()
        self.label_4.setText("机场四字码：")
        layout.addWidget(self.label_4)
        self.combox_4 = ComboBox()


class EmulatorLaunchTool(QWidget):
    def __init__(self, db: LocalCache, parent: Any = None):
        super().__init__(parent)
        self.setWindowTitle("模拟器启动器")
        self.setObjectName("模拟器启动器")

        self.main_layout = QVBoxLayout()

        self.layout1 = QHBoxLayout()

        self.label_java_info = BodyLabel()
        self.label_java_info.setText("Java信息：")
        self.layout1.addWidget(self.label_java_info)

        self.label_java_version = BodyLabel()
        self.layout1.addWidget(self.label_java_version)
        self.label_four_code = BodyLabel()
        self.label_four_code.setText("机场四字码：")
        self.label_four_code_msg = BodyLabel()
        self.layout1.addWidget(self.label_four_code)
        self.layout1.addWidget(self.label_four_code_msg)

        self.button_check_environment = PushButton()
        self.button_check_environment.setText("检查环境")
        self.layout1.addWidget(self.button_check_environment)

        self.layout2 = QHBoxLayout()
        # self.button_draw_path = QtWidgets.QPushButton()
        # self.button_draw_path.setText("画路径")
        self.button_get_airport = PushButton()
        self.button_get_airport.setText("获取机场信息")
        self.layout2.addWidget(self.button_get_airport)

        self.button_draw_path = PushButton()
        self.button_draw_path.setText("画路径")
        self.layout2.addWidget(self.button_draw_path)

        self.button_track_simulation = PushButton()
        self.button_track_simulation.setText("航迹模拟")
        self.layout2.addWidget(self.button_track_simulation)

        self.button_set_aerodrome = PushButton()
        self.button_set_aerodrome.setText("设置机场信息")
        self.layout2.addWidget(self.button_set_aerodrome)

        self.main_layout.addLayout(self.layout1)
        self.main_layout.addLayout(self.layout2)

        self.setLayout(self.main_layout)

        # 机场信息展示部分
        # 下拉框先不用展示出来
        self.h_airport_info = QHBoxLayout()
        self.combo_box = EditableComboBox()
        self.button_sure = PushButton()
        self.button_sure.setText("确认")
        self.h_airport_info.addWidget(self.combo_box)
        self.h_airport_info.addWidget(self.button_sure)

        self.h_rwy_info = QHBoxLayout()
        self.rwy_header_list = ["跑道", ""]
        self.rwy_data_list = []

        self.button_check_environment.clicked.connect(self.check_environment)

        self.button_get_airport.clicked.connect(self.get_airport_info)
        self.button_draw_path.clicked.connect(self.open_draw_path)
        self.button_track_simulation.clicked.connect(self.open_track_simulation)
        self.button_set_aerodrome.clicked.connect(self.set_aerodrome)
        # self.combo_box.clicked.clicked.connect(self.set_aerodrome)

    def open_draw_path(self):
        """
        打开画航迹
        :return:
        """
        print("draw path")

    def open_track_simulation(self):
        """
        打开航迹模拟
        :return:
        """
        print("track simulation")

    def set_aerodrome(self):
        """
        跳转到机场信息设置
        :return:
        """

    def check_environment(self):
        """
        点击java检查环境
        :return:
        """
        sto = subprocess.check_output(["java", "-version"], stderr=subprocess.STDOUT)
        if sto:
            print(sto)
            version_pattern = re.compile(r'java version "([^"]+)"')
            match = version_pattern.search(sto.decode("utf-8"))
            self.label_java_version.setText(match.group(1))
            infos = InfoBar.info(
                title="环境检测",
                content="Java环境正常: \n" "Version: {}".format(match.group(1)),
                orient=Qt.Orientation.Horizontal,
                position=InfoBarPosition.BOTTOM,
                duration=3000,
                parent=self,
            )
            infos.setWindowTitle("Java环境检测结果")
        else:
            infos = InfoBar.warning(
                title="环境检测",
                content="Java环境未安装或路径不正确",
                orient=Qt.Orientation.Horizontal,
                position=InfoBarPosition.BOTTOM,
                duration=3000,
            )
            infos.setWindowTitle("Java环境检测结果")

    def get_airport_info(self):
        """
        获取机场信息
        :return:
        """
        logger.info("get_airport_info")
        layout = QHBoxLayout()
        cache = LocalCache()
        ls_airport = cache.get_airport()  # 获取机场信息
        logger.debug(ls_airport)
        self.combo_box.clear()
        __tmp_name = []
        if ls_airport:
            for i in ls_airport:
                __tmp_name.append(i["name"])
                self.combo_box.addItem(i["name"], userData=i)
        layout.addWidget(self.combo_box)

        self.main_layout.addLayout(layout)

        # 创建补全器
        completer = QCompleter(__tmp_name, self.combo_box)
        # 设置显示的选项数
        completer.setMaxVisibleItems(10)

        # 设置补全器
        self.combo_box.setCompleter(completer)

        # 重新绘制界面
        self.redraw_the_interface()

    def redraw_the_interface(self):
        """
        重新绘制界面
        :return:
        """
        old_layouts = [
            self.main_layout.itemAt(i).layout() for i in range(self.main_layout.count())
        ]
        for i in old_layouts:
            self.main_layout.removeItem(i)

        for i in old_layouts:
            self.main_layout.addLayout(i)

        self.setLayout(self.main_layout)
